//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package testcase_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type LinkSpritDbItem struct {
	LinkId      string `bson:"_id"` //自动生成
	CaseId      string `bson:"caseId"`
	SpritId     string `bson:"spritId"`
	ResultCount uint32 `bson:"resultCount"`
}

type _LinkSpritDao struct {
	mc *mongo.Collection
}

func newLinkSpritDao(db *mongo.Database) (*_LinkSpritDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_TEST_CASE + "link_sprit")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"spritId", 1}},
		},
		{
			Keys: bson.D{{"caseId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_LinkSpritDao{mc: mc}, nil
}

func (db *_LinkSpritDao) Insert(ctx context.Context, dbItem *LinkSpritDbItem) error {
	dbItem.LinkId = db.genLinkId(dbItem.CaseId, dbItem.SpritId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_LinkSpritDao) genLinkId(caseId, spritId string) string {
	return fmt.Sprintf("%s:%s", spritId, caseId)
}

func (db *_LinkSpritDao) Exist(ctx context.Context, caseId, spritId string) (bool, error) {
	linkId := db.genLinkId(caseId, spritId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": linkId})
	return count > 0, err
}

func (db *_LinkSpritDao) Get(ctx context.Context, caseId, spritId string) (*LinkSpritDbItem, error) {
	linkId := db.genLinkId(caseId, spritId)
	retItem := &LinkSpritDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": linkId}).Decode(retItem)
	return retItem, err
}

func (db *_LinkSpritDao) Remove(ctx context.Context, caseId, spritId string) error {
	linkId := db.genLinkId(caseId, spritId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": linkId})
	return err
}

func (db *_LinkSpritDao) RemoveByCase(ctx context.Context, caseId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"caseId": caseId})
	return err
}

func (db *_LinkSpritDao) RemoveBySprit(ctx context.Context, spritId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"spritId": spritId})
	return err
}

func (db *_LinkSpritDao) ListBySprit(ctx context.Context, spritId string) ([]*LinkSpritDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"spritId": spritId})
	if err != nil {
		return nil, err
	}
	retList := []*LinkSpritDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_LinkSpritDao) UpdateResultCount(ctx context.Context, caseId, spritId string, count uint32) error {
	linkId := db.genLinkId(caseId, spritId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": linkId}, bson.M{"$set": bson.M{"resultCount": count}})
	return err
}
